package com.whut.transportation.overweight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.whut.transportation.EntruckDetailActivity;
import com.whut.transportation.R;
import com.whut.transportation.adapter.ReasonAdapter;
import com.whut.transportation.adapter.ReasonAdapter.ViewHolder;
import com.whut.transportation.entity.AllReason;
import com.whut.transportation.entity.DealedWeighingInfo;
import com.whut.transportation.entity.GuDao;
import com.whut.transportation.entity.Message;
import com.whut.transportation.entity.OverWeightInfo;
import com.whut.transportation.entity.Reason;
import com.whut.transportation.entity.ShowDealedWeighInfo;
import com.whut.transportation.network.HttpManager;
import com.whut.transportation.network.HttpRequestVo;
import com.whut.transportation.parser.JSONParser;
import com.whut.transportation.ui.BaseActivity;
import com.whut.transportation.utils.Constant;


public class OverWeightDetailActivity extends BaseActivity {
	
	private SharedPreferences preferences;
	
	private OverWeightInfo overWeightInfo;
	private ShowDealedWeighInfo weighDealingInfo;
	private DealedWeighingInfo dealedWeighingInfo;
	private ShowDealedWeighInfo showDealedWeighInfo;
	
	private TextView owinfo_number;
	private LinearLayout owinfo_line1;
	private TextView owinfo_trainNum;
	private TextView owinfo_traintype;
	private LinearLayout owinfo_line2;
	private TextView owinfo_zaizhong;
	private TextView owinfo_zizhong;
	private LinearLayout owinfo_line3;
	private TextView owinfo_chaoqian;
	private TextView owinfo_pianzai;
	private TextView owinfo_pianzhong;
	
	private Button auto_ow_checktime;
	private EditText ow_detail_finish_data;
	private EditText ow_detail_finish_time_pre;
	private EditText ow_detail_finish_time_last;
	
	private LinearLayout activity_ow_detail;
	private RadioGroup ow_detail_radiogroup1;
	private RadioButton ow_complete_normal;
	private RadioButton ow_complete_errortreatable;
	private RadioButton ow_imcomplete_error;
	
	private View activity_ow_detail_normal;
	private Button ow_detail_submit1;
	
	private View activity_ow_detail_errortreatable;
	private Button ow_detail_submit2;
	
	private View view_popupwindow;
	private LinearLayout popupwindow;
	private Button reason;
	private TextView reasonList;
	private Button submit;
	private Button cancel;
	private ListView list;
	private PopupWindow window;
	private List<Reason> reasons;
	private ReasonAdapter reasonAdapter;
	
	private View activity_ow_detail_error;
	private LinearLayout ow_detail_line3;
	/*private CheckBox ow_detail_checkBox1;
	private CheckBox ow_detail_checkBox2;*/
	private TextView ow_detail_line4;
	private EditText ow_detail_otherReason;
	private Button ow_detail_submit3;
	
	private GuDao gudao;
	
	@Override
	protected void loadViewLayout() {
		setContentView(R.layout.activity_ow_detail);
		activity_ow_detail_normal = View.inflate(mContext, R.layout.activity_ow_detail_normal, null);
		activity_ow_detail_errortreatable = View.inflate(mContext, R.layout.activity_ow_detail_errortreatable, null);
		activity_ow_detail_error = View.inflate(mContext, R.layout.activity_ow_detail_error, null);
		view_popupwindow = View.inflate(mContext, R.layout.popupwindow, null);
		Intent intent = getIntent();
		overWeightInfo = (OverWeightInfo)intent.getSerializableExtra("overWeightInfo");
		gudao = (GuDao)intent.getSerializableExtra("gudao");
		preferences = getSharedPreferences("userId", Context.MODE_PRIVATE);
		setTitleBarView(true, overWeightInfo.getTrainNumber()+overWeightInfo.getTrain()+"超重处理", -1, true);
	}
	@Override
	protected void findViewById() {
		owinfo_number = (TextView) findViewById(R.id.owinfo_number);
		owinfo_line1 = (LinearLayout) findViewById(R.id.owinfo_line1);
		owinfo_trainNum = (TextView) findViewById(R.id.owinfo_trainNum);
		owinfo_traintype = (TextView) findViewById(R.id.owinfo_traintype);
		owinfo_line2 = (LinearLayout) findViewById(R.id.owinfo_line2);
		owinfo_zaizhong = (TextView) findViewById(R.id.owinfo_zaizhong);
		owinfo_zizhong = (TextView) findViewById(R.id.owinfo_zizhong);
		owinfo_line3 = (LinearLayout) findViewById(R.id.owinfo_line3);
		owinfo_chaoqian = (TextView) findViewById(R.id.owinfo_chaoqian);
		owinfo_pianzai = (TextView) findViewById(R.id.owinfo_pianzai);
		owinfo_pianzhong = (TextView) findViewById(R.id.owinfo_pianzhong);

		activity_ow_detail = (LinearLayout) findViewById(R.id.activity_ow_detail);
		ow_detail_radiogroup1 = (RadioGroup) findViewById(R.id.ow_detail_radiogroup1);
		ow_complete_normal = (RadioButton) findViewById(R.id.ow_complete_normal);
		ow_complete_errortreatable=(RadioButton) findViewById(R.id.ow_complete_errortreatable);
		ow_imcomplete_error = (RadioButton) findViewById(R.id.ow_imcomplete_error);
		
		auto_ow_checktime = (Button) findViewById(R.id.auto_ow_checktime);
		ow_detail_finish_data = (EditText) findViewById(R.id.ow_detail_finish_date);
		ow_detail_finish_time_pre = (EditText) findViewById(R.id.ow_detail_finish_time_pre);
		ow_detail_finish_time_last = (EditText) findViewById(R.id.ow_detail_finish_time_last);
		ow_detail_submit1 = (Button) activity_ow_detail_normal.findViewById(R.id.ow_detail_submit1);
		
		ow_detail_submit2 = (Button) activity_ow_detail_errortreatable.findViewById(R.id.ow_detail_submit2);
		
		ow_detail_line3 = (LinearLayout) activity_ow_detail_error.findViewById(R.id.ow_detail_line3);
		reason= (Button) activity_ow_detail_error.findViewById(R.id.reason);
		reasonList=(TextView) activity_ow_detail_error.findViewById(R.id.textView2);
		ow_detail_otherReason = (EditText) activity_ow_detail_error.findViewById(R.id.ow_detail_otherReason);
		ow_detail_line4 = (TextView) activity_ow_detail_error.findViewById(R.id.ow_detail_line4);
		ow_detail_submit3 = (Button) activity_ow_detail_error.findViewById(R.id.ow_detail_submit3);
		
		 list=(ListView)view_popupwindow.findViewById(R.id.lv);  
		 submit = (Button) view_popupwindow.findViewById(R.id.submit);  
		 cancel = (Button) view_popupwindow.findViewById(R.id.cancel);  
	}

	@Override
	protected void afterFindViewId() {
		owinfo_number.setText(owinfo_number.getText()+overWeightInfo.getShunNumber());
		owinfo_trainNum.setText(owinfo_trainNum.getText()+overWeightInfo.getTrainNumber());
		owinfo_traintype.setText(owinfo_traintype.getText()+overWeightInfo.getTrain());
		owinfo_zaizhong.setText(owinfo_zaizhong.getText()+""+overWeightInfo.getZaizhong()+"t");
		owinfo_zizhong.setText(owinfo_zizhong.getText()+""+overWeightInfo.getZizhong()+"t");
		owinfo_chaoqian.setText(owinfo_chaoqian.getText()+""+overWeightInfo.getChaoqian()+"t");
		owinfo_pianzai.setText(owinfo_pianzai.getText()+""+overWeightInfo.getPianzai()+"t");
		owinfo_pianzhong.setText(owinfo_pianzhong.getText()+""+overWeightInfo.getPianzhong()+"t");
	}

	@Override
	protected void processLogic() {
		findDealedWeighInfo();
		getAllReason();
	}

	private void findDealedWeighInfo() {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.FIND_WEIGHDEALING_INFO;
		vo.context = mContext;
		
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("weighDealingInfo.danma", overWeightInfo.getDanma());
		req.put("weighDealingInfo.shunhao", overWeightInfo.getShunNumber());
		vo.requestDataMap = req;
		vo.parser = new JSONParser(ShowDealedWeighInfo.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(HashMap<String, Object> paramObject,boolean paramBoolean) {
						showDealedWeighInfo = (ShowDealedWeighInfo) paramObject.get("result");
						if (showDealedWeighInfo.getMessage() != -1) {
							String  timeFinish = showDealedWeighInfo.getDealtime().trim();
							if(timeFinish.length()==16){
								String[] s1 = timeFinish.split(" ");
								ow_detail_finish_data.setText(s1[0]);
								String[] s2 = s1[1].split(":");
								ow_detail_finish_time_pre.setText(s2[0]);
								ow_detail_finish_time_last.setText(s2[1]);
							}
							if (showDealedWeighInfo.getMessage() == 2) {
								//ow_detail_radiogroup1.check(R.id.ow_imcomplete_error);
								String description = showDealedWeighInfo.getDescription().trim();
								ow_detail_otherReason.setText(description);
							} 
						} 
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}
	@Override
	protected void setListener() {
		auto_ow_checktime.setOnClickListener(this);
		ow_detail_submit1.setOnClickListener(this);
		ow_detail_submit2.setOnClickListener(this);
		ow_detail_submit3.setOnClickListener(this);
		ow_detail_radiogroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int radioButtonId = group.getCheckedRadioButtonId();
				switch (radioButtonId) {
				case R.id.ow_complete_normal:	
					activity_ow_detail.removeView(activity_ow_detail_error);
					activity_ow_detail.removeView(activity_ow_detail_errortreatable);
					activity_ow_detail.addView(activity_ow_detail_normal);
					break;
				case R.id.ow_complete_errortreatable:
					activity_ow_detail.removeView(activity_ow_detail_normal);
					activity_ow_detail.removeView(activity_ow_detail_error);
					activity_ow_detail.addView(activity_ow_detail_errortreatable);
					break;
				case R.id.ow_imcomplete_error:
					activity_ow_detail.removeView(activity_ow_detail_errortreatable);
					activity_ow_detail.removeView(activity_ow_detail_normal);
					activity_ow_detail.addView(activity_ow_detail_error);
					break;
				default:
					break;
				}
			}
		});
		reason.setOnClickListener(this);
		/*reason.setOnClickListener(bPop);
		submit.setOnClickListener(submitListener);  
        cancel.setOnClickListener(cancelListener);  */
        //list.setOnItemClickListener(listClickListener);
	}
	  OnClickListener bPop = new OnClickListener() {  
	        @Override  
	        public void onClick(View v) {  
	            popAwindow(v);  
	        }  
	    };  
	private void popAwindow(View parent) {  
      if (window == null) {  
      	view_popupwindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_corners_pop));  
          window = new PopupWindow(view_popupwindow, 450,260);  
      }  
        
      //设置整个popupwindow的样式。  
      window.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_corners_pop));  
      //使窗口里面的空间显示其相应的效果，比较点击button时背景颜色改变。  
      //如果为false点击相关的空间表面上没有反应，但事件是可以监听到的。  
      //listview的话就没有了作用。  
      window.setFocusable(true);//如果不设置setFocusable为true，popupwindow里面是获取不到焦点的，那么如果popupwindow里面有输入框等的话就无法输入。  
      window.update();  
      //window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);  
      window.showAsDropDown(reason, 0, 0);
  }  

	 OnItemClickListener listClickListener = new OnItemClickListener() {  
	        @Override  
	        public void onItemClick(AdapterView<?> parent, View view, int position,  
	                long id) {  
	            ViewHolder vHollder = (ViewHolder) view.getTag();  
	            // 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。  
	            vHollder.cBox.toggle();  
	            ReasonAdapter.isSelected.put(position, vHollder.cBox.isChecked());   
	           //values.add(vHollder.cBox.getText().toString());
	        }  
	    };  
  OnClickListener submitListener = new OnClickListener() {  
      @Override  
      public void onClick(View v) {  
      	 List<String> values = new ArrayList<String>();
      	for(int i=0;i<list.getCount();i++){
      		if(ReasonAdapter.isSelected.get(i)){
      			ViewHolder vHollder = (ViewHolder) list.getChildAt(i).getTag(); 
      			 values.add(vHollder.title.getText().toString());
      		}
      	}
          //这儿可以写提交数据的代码。 
      	reasonList.setText(values.toString());
        closeWindow();  
      }  
  };  

  OnClickListener cancelListener=new OnClickListener(){  
      @Override  
      public void onClick(View v){  
          closeWindow();  
      }  
  };  
    
  private void closeWindow(){  
  	
  	//将每个checkbox的标记改为false，以便下次弹出window时是初始的状态。  
      for (int j = 0; j < ReasonAdapter.isSelected.size(); j++) {  
      	if(ReasonAdapter.isSelected.get(j)){
      		ReasonAdapter.isSelected.put(j, false);  
      		 ViewHolder vHollder = (ViewHolder) list.getChildAt(j).getTag();  
               vHollder.cBox.setChecked(false);  
      	}
      }  
      //提交数据时关闭popupwindow。  
      if (window != null) {  
          window.dismiss();  
      }  
  }  

	@Override
	protected void getDataAgain() {
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.auto_ow_checktime:
			showChecktime();
			break;
		case R.id.ow_detail_submit1:
			normalSubmit();
			Intent returnHome = new Intent(this,OWTransInfoActivity.class);
			returnHome.putExtra("gudao", gudao);
			startActivity(returnHome);
			finish();
			break;
		case R.id.ow_detail_submit2:
			errortreatableSubmit();
			Intent returnHome2 = new Intent(this,OWTransInfoActivity.class);
			returnHome2.putExtra("gudao", gudao);
			startActivity(returnHome2);
			finish();
			break;
		case R.id.ow_detail_submit3:
			errorSubmit();
			break;
		case R.id.reason:
			toDialog();
			break;
		default:
			break;
		}
		super.onClick(v);
	}
	

	private void showChecktime() {
		Date date = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("HH");
		SimpleDateFormat df2 = new SimpleDateFormat("mm");
		SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");
		String hh = df1.format(date);
		String mm = df2.format(date);
		String d = df3.format(date);
		ow_detail_finish_time_pre.setText(hh);
		ow_detail_finish_time_last.setText(mm);
		ow_detail_finish_data.setText(d);
	}
	
	//未超重情况
	private void normalSubmit() {
		 AlertDialog.Builder builder = new AlertDialog.Builder(OverWeightDetailActivity.this);
		 builder.setTitle("提醒");
		 builder.setMessage("确定提交吗？");
		 builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String dealtime = ow_detail_finish_data.getText().toString().trim()+" "+ow_detail_finish_time_pre.getText().toString().trim()
						+":"+ow_detail_finish_time_last.getText().toString().trim();
				saveWeighDealingInfo("0",dealtime,null,null);
			}
		 });
		 builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
             @Override
             public void onClick(DialogInterface dialog, int which)
             {
             }
         });
		 builder.show();
		
	}

	//超重可处理情况
	private void errortreatableSubmit() {
		 AlertDialog.Builder builder = new AlertDialog.Builder(OverWeightDetailActivity.this);
		 builder.setTitle("提醒");
		 builder.setMessage("确定提交吗？");
		 builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String dealtime = ow_detail_finish_data.getText().toString().trim()+" "+ow_detail_finish_time_pre.getText().toString().trim()
						+":"+ow_detail_finish_time_last.getText().toString().trim();
				saveWeighDealingInfo("1", dealtime,null,null);
			}
		 });
		 builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
             @Override
             public void onClick(DialogInterface dialog, int which)
             {
             }
         });
		 builder.show();
		
	}
	
	//超重不可处理需甩车情况
	private void errorSubmit() {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(OverWeightDetailActivity.this);
		 builder.setTitle("提醒");
		 builder.setMessage("确定提交吗？");
		 builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String dealtime = ow_detail_finish_data.getText().toString().trim()+" "+ow_detail_finish_time_pre.getText().toString().trim()
						+":"+ow_detail_finish_time_last.getText().toString().trim();
				String description = ow_detail_otherReason.getText().toString().trim()+reasonList.getText();
				saveWeighDealingInfo("2", dealtime,null,description);
				Intent uploadPhone = new Intent(OverWeightDetailActivity.this,OWUploadPhoneActivity.class);
				uploadPhone.putExtra("overWeightInfo",overWeightInfo);
				uploadPhone.putExtra("showDealedWeighInfo",showDealedWeighInfo);
				uploadPhone.putExtra("gudao", gudao);
				startActivity(uploadPhone);
			}
		 });
		 builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
            }
        });
		 builder.show();
		
		
	}
	
	private void saveWeighDealingInfo(String result, String dealtime,String imageLink, String description) {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.SAVE_WEIGHDEALING_INFO;
		vo.context = mContext;
		vo.parser = new JSONParser(Message.class);
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("userId", preferences.getString("account", null));
		req.put("weighDealingInfo.danma",overWeightInfo.getDanma());
		req.put("weighDealingInfo.shunhao",overWeightInfo.getShunNumber());
		req.put("weighDealingInfo.gudao",gudao.getGudao());
		req.put("result", result);
		req.put("weighDealingInfo.dealtime", dealtime);
		if(showDealedWeighInfo.getMessage()!=0)
			req.put("dealedWeighingInfo.weighDealingNo", showDealedWeighInfo.getWeighDealingNo());
		req.put("dealedWeighingInfo.description", description);
		vo.requestDataMap = req;
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
				@Override
				public void onStart() {
				}
				@Override
				public void onFailed() {
					showNetErrorDialog();
				}
				@Override
				public void processData(HashMap<String, Object> paramObject,boolean paramBoolean) {
					Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
				}
				@Override
				public void onFinish() {
					closeProgressDialog();
				}
		});
	}
	
	/**
	 * 查询车辆损坏的所有原因
	 */
	private void getAllReason() {
		reasons = new ArrayList<Reason>();
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.FIND_REASON_UNLOAD;
		vo.context = mContext;
		//HashMap<String, String> req = new HashMap<String, String>();
		vo.requestDataMap = null;
		vo.parser = new JSONParser(AllReason.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo, 
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						AllReason allReason = (AllReason) paramObject.get("result");
						reasons.addAll(allReason.ListReason);
						
						if(list.getAdapter()==null){
							reasonAdapter = new ReasonAdapter(mContext,reasons);
							list.setAdapter(reasonAdapter);
							list.setItemsCanFocus(false);  
					        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);  
						}else{
							reasonAdapter.notifyDataSetChanged();
						}
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}
	
	
	public void toDialog(){
		Intent intent = new Intent();
		intent.setClass(OverWeightDetailActivity.this, DialogActivity.class);
		startActivityForResult(intent, 1);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		reasonList.setText(data.getExtras().getString("resultValue"));
	}
}

